'use strict';

const Controller = require('egg').Controller;

class UserController extends Controller {

  // 用户登录
  async login() {
    const { ctx, service, app } = this;
    const { uname, pwd } = ctx.query;
    const id = await service.user.login(uname, pwd);
    if (id !== -1) {
      ctx.body = {
        token: app.jwt.sign({ typ: 'jwt', id }, app.config.jwt.secret),
        code: 200,
      };
    } else {
      ctx.body = {
        code: 403,
      };
    }
  }

  // 联合查询 users union dparts
  async getUsersUdparts() {
    const { ctx, service } = this;
    const users = await service.user.getUsersUdparts();
    ctx.body = {
      count: users.length,
      users,
    };
  }

  // 获取user
  async getUser() {
    const { ctx, service } = this;
    const { id } = ctx.params;
    const user = await service.user.getUser(id);
    ctx.body = {
      user,
    };
  }

  // 删除user
  async delUser() {
    const { ctx, service } = this;
    const { id } = ctx.params;
    try {
      await service.user.delUser(id);
    } catch (error) {
      console.error(error);
    }
    ctx.body = {
      msg: 'ok',
    };
  }

  // 新增user
  async addUser() {
    const { ctx, service } = this;
    const { uname, pwd, cn, dpart, state, sex, phone, email } = ctx.query;
    await service.user.addUser(uname, pwd, cn, dpart, state, sex, phone, email);
    ctx.body = {
      msg: 'ok',
    };
  }

  // 修改user
  async updateUser() {
    const { ctx, service } = this;
    const { pwd, cn, dpart, state, sex, phone, email, id } = ctx.query;
    await service.user.updateUser(pwd, cn, dpart, state, sex, phone, email, id);
    ctx.body = {
      msg: 'ok',
    };
  }

  // 搜索框查询
  async searchUsers() {
    const { ctx, service } = this;
    const { kw } = ctx.query;
    const users = await service.user.searchUsers(kw);
    ctx.body = {
      count: users.length,
      users,
    };
  }
}

module.exports = UserController;
